const http = require("http");
const fs = require("fs");
import formidable, { errors as formidableErrors } from "formidable";
import path from "path";
import { desktopPath } from "./render";

const hostname = "127.0.0.1";
const port = 8080;

export const runServer = () =>
  server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
  });

export const closeServer = () => {
  console.log("close server");
  server.close();
};

const server = http.createServer((req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.setHeader("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  res.statusCode = 200;

  if (req.method.toLowerCase() === "options") {
    res.end();
    return;
  }

  if (req.url.indexOf("/local") > -1) {
    req.url = req.url.replace("/local", "");
    if (req.url.endsWith("js")) {
      res.setHeader("Content-Type", "application/javascript");
    }
    fs.readFile(path.join("out/renderer", req.url), (err, data) => {
      if (err) throw err;
      res.end(data);
    });
    return;
  }

  switch (req.url) {
    case "/upload":
      if (req.method.toLowerCase() === "post") upload(req, res);
      break;
    default:
      let link = path
        .join(desktopPath.path, "web/res/img", req.url)
        .replace(/\//g, "\\");
      if (!fs.existsSync(link) || fs.statSync(link).isDirectory()) {
        console.log(link, "does not exist");
        res.end();
        return;
      }
      fs.readFile(link, (err, data) => {
        if (err) throw err;
        res.end(data);
      });
      break;
  }
});

const upload = async (req, res) => {
  const form = formidable({});
  const [fields, files] = await form.parse(req);
  let fileName = "";
  const el = files["wangeditor-uploaded-image"][0];
  if (el.originalFilename.indexOf("/") > -1)
    fileName = el.originalFilename.substring(
      el.originalFilename.lastIndexOf("/") + 1
    );
  else fileName = el.originalFilename;

  fs.copyFileSync(
    el.filepath,
    path.join(desktopPath.path, "web/res/img/" + fileName)
  );

  res.setHeader("Content-Type", "application/json");
  res.end(
    JSON.stringify({
      errno: 0, // 注意：值是数字，不能是字符串
      data: {
        url: "http://127.0.0.1:8080/" + fileName,
      },
    })
  );
};
